package prototyping;

import java.rmi.RMISecurityManager;

import net.jini.core.discovery.LookupLocator;
import net.jini.core.entry.Entry;
import net.jini.core.lookup.ServiceRegistrar;
import net.jini.core.lookup.ServiceTemplate;
import net.jini.lookup.entry.Name;
import net.jini.space.JavaSpace;

public class TestJSpace {
	private static final long WAITFOR = 100000L;

	public static void main(String[] args) {
		try {
			SpaceItem msg = new SpaceItem("Hello there");
			System.out.println("Searching for a JavaSpace...");
			JavaSpace space = findSpace("JERI_Group0");
			System.out.println("Writing a message into the space...");
			space.write(msg, null, 60 * 60 * 1000);
			SpaceItem template = new SpaceItem();
			System.out.println("Reading a message from the space...");
			SpaceItem result = (SpaceItem) space.read(template, null,
					Long.MAX_VALUE);
			System.out.println("The message read is: " + result.content);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	static public JavaSpace findSpace(String spaceName) throws Exception {
		// Get a RMI security manger, if doesn't exist set a new one.
		// The security policy is passed to this security manager using the
		// -Djava.security.policy flag.
		System.setProperty("java.security.policy",
				"/home/sebbe/School/Distributed_Computing/DSJini/DSJini/test.policy");
		if (System.getSecurityManager() == null)
			System.setSecurityManager(new RMISecurityManager());

		// Create a template to lookup the JavaSpaces service.
		Class[] classes = new Class[] { net.jini.space.JavaSpace.class };
		Name sn = new Name(spaceName);
		ServiceTemplate tmpl = new ServiceTemplate(null, classes,
				new Entry[] { sn });

		// Locate the JavaSpaces service and create a JavaSpace proxy attached
		// to it.
		LookupLocator locator = new LookupLocator("jini://localhost");
		ServiceRegistrar sr = locator.getRegistrar();
		JavaSpace space = (JavaSpace) sr.lookup(tmpl);

		return space;
	}
}
